// content.js

// 监听来自popup.js的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === "execute") {
    // 执行相应的操作
    const list = performOperation(message.data?.rule);
    // 将结果发送回popup页面
    chrome.runtime.sendMessage({
      action: "result",
      data: list,
    });
  }
});

// 执行操作
function performOperation(rule) {
  const list = [];
  try {
    const images = document.querySelectorAll(rule || "img");
    for (let i = 0; i < images.length; i++) {
      list.push(images[i].src);
    }
  } catch (e) {
    console.error("规则错误：", e);
    return list;
  }
  return list;
}

console.log("content.js");

// ----------------------------------------------------------------------

function getStorage(key = "list") {
  const str = localStorage.getItem(key);
  return str ? JSON.parse(str) : [];
}

function setStorage(key = "list", value = list) {
  localStorage.setItem(key, JSON.stringify(value));
}

// 获取url参数值
function getUrlParam(key, url = window.location.href) {
  try {
    // 创建一个新的URL对象
    const urlObject = new URL(url);
    // 使用URLSearchParams对象获取查询参数
    const params = new URLSearchParams(urlObject.search);
    // 返回查询参数的值
    return params.get(key);
  } catch (error) {
    console.error("Invalid URL:", error);
    return null;
  }
}

// 节流函数
function throttle(func, delay) {
  let lastTime = 0;

  return function (...args) {
    const now = new Date().getTime();
    if (now - lastTime >= delay) {
      lastTime = now;
      func.apply(this, args);
    }
  };
}
